#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <sys/types.h>
#include <sys/socket.h>
#include <functional>
#include "InetAddr.hpp"
#include "LockGuard.hpp"
#include "ThreadPool.hpp"

using task_t = std::function<void()>;

class MessageRout
{
private:
    bool IsExist(const InetAddr &user)
    {

        for (auto addr : _online_user)
        {
            if (addr == user)
            {
                return true;
            }
        }
        return false;
    }

public:
    MessageRout()
    {
            
        pthread_mutex_init(&_mutex, nullptr);
    }

    void AddUser(const InetAddr &user)
    {
  

        // 可能有多个用户同时添加所以要加锁
        LockGuard lock(&_mutex);
        if (IsExist(user))
            return;

        _online_user.push_back(user);
    }

    void DelUser(const InetAddr &user)
    {
        LockGuard lock(&_mutex);
        for (auto it = _online_user.begin(); it != _online_user.end(); it++)
        {
            if (*it == user)
            {
                _online_user.erase(it);
                break;
            }
        }
    }

    void RouteHelper(int socketfd, InetAddr user, const std::string msg)
    {
        LockGuard lock(&_mutex);
        // 消息转发
        for (auto addr : _online_user)
        {

            std::string send_message = "\n[" + user.GetIp() + ":" + std::to_string(user.GetPort()) + "]" + msg + "\n";
            // 获得每一个客户端地址
            struct sockaddr_in clientaddr = addr.GetAddr();
            ::sendto(socketfd, send_message.c_str(), send_message.size(), 0, (struct sockaddr *)&clientaddr, sizeof(clientaddr));
        }
    }

    void Route(int socketfd, const InetAddr user, const std::string msg)
    {
        // 用户首次发任务时候添加用户
        AddUser(user);
       

        // 如果客户端退出
        if (msg == "exit")
        {
            DelUser(user);
        }

        // 构建任务对象，入队列，让线程池进行转发
        task_t task = std::bind(&MessageRout::RouteHelper, this, socketfd, user, msg);
        ThreadPool<task_t>::GetInstance()->Enqueue(task);
    }

    ~MessageRout()
    {
        pthread_mutex_destroy(&_mutex);
    }

private:
    std::vector<InetAddr> _online_user; // 在线用户
    pthread_mutex_t _mutex;
};